package com.test.utils;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class DBUtil {

	private static final String URL = "jdbc:mysql://localhost:3306/test?"
			+ "user=root&password=root&useUnicode=true&oldsyntax=true&characterEncoding=UTF8";

	public static Connection connection = null;
	public static PreparedStatement pstmt = null;
	public static ResultSet rs = null;

	public static Connection getConnection() throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");
		return (Connection) DriverManager.getConnection(URL);
	}

	public static PreparedStatement paPreparedStatement(String sql, Object[] params)
			throws SQLException, ClassNotFoundException {

		pstmt = (PreparedStatement) getConnection().prepareStatement(sql);
		if (null != params) {
			for (int i = 0; i < params.length; i++) {
				pstmt.setObject(i + 1, params[i]);
			}
		}
		return pstmt;
	}

	// 通用增删改
	public static boolean executeUpdate(String sql, Object[] params) {

		try {

			pstmt = paPreparedStatement(sql, params);
			int count = pstmt.executeUpdate();
			if (count > 0)
				return true;
			else
				return false;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (pstmt != null)
					pstmt.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	// 通用查
	public static ResultSet executeQuery(String sql, Object[] params) {

		try {

			pstmt = paPreparedStatement(sql, params);
			rs = pstmt.executeQuery();

			return rs;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}

	}
}
